package com.cisdi.blog.web.admin;

import com.cisdi.blog.exception.NotFoundException;
import com.cisdi.blog.vo.FileVO;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.BatchStatus;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author pengyangyan
 * @version 1.0.0
 * @date 2020年04月20日 11:29:00
 */
@Controller
@RequestMapping("/admin/file")
public class FileController {

    @Value("${qiniu.ak}")
    private String ak;
    @Value("${qiniu.sk}")
    private String sk;
    @Value("${qiniu.bucket}")
    private String bucket;
    @Value("${qiniu.domain}")
    private String domain;

    @PostMapping("/upload")
    public String uploadFile(MultipartFile file,RedirectAttributes attributes) throws IOException {
        Configuration configuration = new Configuration(Region.autoRegion());
        UploadManager uploadManager = new UploadManager(configuration);
        byte[] bytes = file.getBytes();
        String suffex = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));


        Auth auth = Auth.create(ak,sk);
        String token = auth.uploadToken(bucket);

        String key = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))+new Random().nextInt(10)+suffex;

        try {
            Response response = uploadManager.put(bytes, key, token);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
            attributes.addFlashAttribute("status",true);
            attributes.addFlashAttribute("message","上传成功");
        } catch (QiniuException e) {
            e.printStackTrace();
            attributes.addFlashAttribute("status",false);
            attributes.addFlashAttribute("message","上传失败");
            return "redirect:/admin/file/input";
        }
        return "redirect:/admin/file/list";
    }

    @ResponseBody
    @RequestMapping("/blog/upFile")
    public Map<String, Object> articleUpFile(HttpServletRequest req, @RequestParam("editormd-image-file") MultipartFile picpaths) throws IOException {
        Map<String, Object> resultJs = new HashMap<>();
        Configuration configuration = new Configuration(Region.autoRegion());
        UploadManager uploadManager = new UploadManager(configuration);
        byte[] bytes = picpaths.getBytes();
        String suffex = Objects.requireNonNull(picpaths.getOriginalFilename()).substring(picpaths.getOriginalFilename().lastIndexOf("."));


        Auth auth = Auth.create(ak,sk);
        String token = auth.uploadToken(bucket);

        String key = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmm"))+new Random().nextInt(10)+suffex;

        try {
            Response response = uploadManager.put(bytes, key, token);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
            resultJs.put("success", 1);
            resultJs.put("message", "上传成功");
            resultJs.put("url",domain + putRet.key);
        } catch (QiniuException e) {
            resultJs.put("success", 0);
            resultJs.put("message", "上传失败");
        }
        return resultJs;
    }

    @GetMapping("/input")
    public String input(){
        return "admin/file_upload";
    }

    @GetMapping("/list")
    public String listFile(Model model){
        List<FileVO> list = new ArrayList<>();
        Configuration configuration = new Configuration(Region.autoRegion());
        Auth auth = Auth.create(ak,sk);
        BucketManager bucketManager = new BucketManager(auth, configuration);
        String prefix = "";
        int limit = 1000;
        String delimiter = "";
        //列举空间文件列表
        BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(bucket, prefix, limit, delimiter);
        while (fileListIterator.hasNext()) {
            //处理获取的file list结果
            FileInfo[] items = fileListIterator.next();
            for (FileInfo item : items) {
                FileVO fileVO = new FileVO();
                fileVO.setFileName(item.key);
                fileVO.setType(item.mimeType);
                fileVO.setUrl(domain+item.key);
                list.add(fileVO);
            }
        }
        model.addAttribute("list",list);
        return "admin/files";
    }

    @GetMapping("/delete/{filename}")
    public String deleteFile(@PathVariable String filename, RedirectAttributes attributes){
        Configuration configuration = new Configuration(Region.autoRegion());
        Auth auth = Auth.create(ak, sk);
        BucketManager bucketManager = new BucketManager(auth, configuration);
        try {
            //单次批量请求的文件数量不得超过1000
            String[] keyList = new String[]{filename};
            BucketManager.BatchOperations batchOperations = new BucketManager.BatchOperations();
            batchOperations.addDeleteOp(bucket, keyList);
            Response response = bucketManager.batch(batchOperations);
            BatchStatus[] batchStatusList = response.jsonToObject(BatchStatus[].class);
            BatchStatus status = batchStatusList[0];
            if (status.code == 200) {
                attributes.addFlashAttribute("status",true);
                attributes.addFlashAttribute("message","删除成功");
            } else {
                attributes.addFlashAttribute("status",false);
                attributes.addFlashAttribute("message","删除失败");

            }
        } catch (QiniuException ex) {
            System.err.println(ex.response.toString());
        }
        return "redirect:/admin/file/list";
    }


}
